<?php
class smallTools {
	function __construct() {
		$option = get_option('smalltool');
		$option = json_decode($option, true);
		if(!empty($option)) {
			foreach($option as $name) {
				if(!method_exists($this, $name)) continue;
				$this->$name();
			}
		}
	}

	//禁用Google Open Sans字体
	private function open_sans() {
		add_filter('gettext_with_context', function($translations, $text, $context, $domain) {
			if('Open Sans font: on or off' == $context && 'on' == $text) {
				$translations = 'off';
			}
			return $translations;
		}, 10, 4);
	}

	//禁用emoji表情
	private function emoji() {
		add_action('init', function() {
			remove_action('admin_print_scripts', 'print_emoji_detection_script');
			remove_action('admin_print_styles', 'print_emoji_styles');
			remove_action('wp_head', 'print_emoji_detection_script', 7);
			remove_action('wp_head', 'wp_resource_hints', 2);
			remove_action('wp_print_styles', 'print_emoji_styles');
			remove_filter('the_content_feed', 'wp_staticize_emoji');
			remove_filter('comment_text_rss', 'wp_staticize_emoji');
			remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
		});
	}

	//开启友情链接管理
	private function link_manage() {
		add_filter('pre_option_link_manager_enabled', '__return_true');
	}

	//关闭前台顶部工具条
	private function admin_bar() {
		add_filter('show_admin_bar', '__return_false');
	}

	//禁止向站内链接发送 PingBack 引用通告
	private function pingback() {
		add_action('pre_ping', function(&$links) {
			$home = get_option('home');
			foreach($links as $key => $val) {
				if(0 === strpos($val, $home)) unset($links[$key]);
			}
		});
	}

	//移除 XML-RPC
	private function xml_rpc() {
		remove_action('wp_head', 'rsd_link');
	}

	//禁用 XML-RPC 接口
	private function xml_rpc_api() {
		add_filter('xmlrpc_enabled', '__return_false');
	}

	//移除 Windows Live Writer
	private function windows_live_writer() {
		remove_action('wp_head', 'wlwmanifest_link');
	}
	
	//移除前台head标签中显示WP版本号
	private function wp_version() {
		remove_action('wp_head', 'wp_generator');
	}

	//移除JS/CSS版本号
	private function css_js_version() {
		add_filter('style_loader_src', function($src){
			if(strpos($src, 'ver=')) {
				$src = remove_query_arg('ver', $src);
			}
			return $src;
		}, 10, 1);
		
		add_filter('script_loader_src', function($src){
			if(strpos($src, 'ver=')) {
				$src = remove_query_arg('ver', $src);
			}
			return $src;
		}, 10, 1);
	}

	//移除短链接
	private function wp_shortlink() {
		remove_action('wp_head', 'wp_shortlink_wp_head');
	}

	//移除后台登录错误提示
	private function login_errors() {
		add_filter('login_errors', function($errors){
			return '发生错误，请检查账号密码是否正确';
		});
	}

	//删除仪表盘活动模块
	private function dashboard_activity() {
		add_action('wp_dashboard_setup', function(){
			global $wp_meta_boxes;
			unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_activity']);
		});
	}

	//删除仪表盘新闻模块
	private function dashboard_primary() {
		add_action('wp_dashboard_setup', function(){
			global $wp_meta_boxes;
			unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
		});
	}

	//删除仪表盘欢迎模块
	private function welcome_panel() {
		remove_action('welcome_panel', 'wp_welcome_panel');
	}

	//删除文章编辑页面模块
	private function post_trackbacksdiv() {
		add_action('admin_init', function() {
			remove_meta_box('trackbacksdiv', 'post', 'normal');
		});
	}

	//删除文章编辑页面自定义字段模块
	private function post_postcustom() {
		add_action('admin_init', function() {
			remove_meta_box('postcustom', 'post', 'normal');
		});
	}

	//移除WP自动修正大小写
	private function capital_P_dangit() {
		remove_filter('the_content', 'capital_P_dangit');
		remove_filter('the_title', 'capital_P_dangit');
		remove_filter('comment_text', 'capital_P_dangit');
	}

	//禁止WP文章修订版
	private function wp_revisions_to_keep() {	
		add_action('wp_print_scripts', function() {
			wp_deregister_script('autosave');
		});
		add_filter('wp_revisions_to_keep', function($num, $post) {
			return 0;
		}, 10, 2);
	}

	//禁止前台加载语言包
	private function no_lang() {
		add_filter('locale', function($locale) {
			$locale = is_admin() ? $locale : 'en_US';
			return $locale;
		});
	}

	//禁止定时任务
	private function no_cron() {
		remove_action('init', 'wp_cron');
	}

	//使用经典编辑器
	private function editor() {
		add_filter('use_block_editor_for_post', '__return_false');
	}

	//禁用 auto-embeds
	private function auto_embeds() {
		remove_filter('the_content', array($GLOBALS['wp_embed'], 'autoembed'));
	}

	//禁用 post embed
	private function post_embed() {
		remove_action('rest_api_init', 'wp_oembed_register_route');
		remove_filter('rest_pre_serve_request', '_oembed_rest_pre_serve_request');
		remove_filter('oembed_dataparse', 'wp_filter_oembed_result');
		remove_filter('oembed_response_data', 'get_oembed_response_data_rich');
		remove_action('wp_head', 'wp_oembed_add_discovery_links');
		remove_action('wp_head', 'wp_oembed_add_host_js');
	}

	//重命名上传文件
	private function file_name() {
		add_filter('sanitize_file_name', function($filename) {
			$fileinfo = pathinfo($filename);
			$ext = empty($fileinfo['extension']) ? '' : '.' . $fileinfo['extension'];
			$name = basename($filename, $ext);
			if(!preg_match('/^[0-9a-zA-Z_-]+$/', $name)) $name = md5($name);
			return $name . $ext;
		});
	}

	//不搜索页面
	private function search_filter_page() {
		add_filter('pre_get_posts', function($query) {
			if($query->is_search) {
				$query->set('post_type', 'post');
			}
			return $query;
		});
	}

	//评论回复邮件通知
	private function comment_mail_notify() {
		add_action('comment_post', function($comment_id) {
			$comments = get_comment($comment_id);
			$parent_id = $comments->comment_parent ? $comments->comment_parent : '';
			if(!$parent_id) return;
	
			$blog_name = get_bloginfo('name');
			$admin_email = get_bloginfo('admin_email');
	
			$parent_comments = get_comment($parent_id);
	
			$mail_title = sprintf('%s 您在《%s》上的评论有了新回复', $parent_comments->comment_author, $blog_name);
			$headers = array(
				'Content-Type: text/html; charset=UTF-8',
				'From: ' . $blog_name . ' <' . $admin_email . '>',
			);
			$comment_link = get_comment_link($comment_id, array('type' => 'comment'));
			$mail_txt = sprintf('<p>%s 您好！</p><p>您曾在《%s》的评论有了新的回复，您的评论内容为：</p><blockquote>%s</blockquote><p>回复内容为：</p><blockquote>%s</blockquote><p>您可以点击下面的链接查看详细内容：<br /><a href="%s">%s</a></p>',
				$parent_comments->comment_author,
				get_the_title($comments->comment_post_ID),
				$parent_comments->comment_content,
				$comments->comment_content,
				$comment_link,
				$comment_link
			);
			wp_mail($parent_comments->comment_author . ' <' . $parent_comments->comment_author_email . '>', $mail_title, $mail_txt, $headers);
		}, 10, 1);
	}
	
	//禁止裁剪缩略图尺寸medium_large
	private function no_medium_large() {
		add_filter('intermediate_image_sizes_advanced', function($sizes) {
			unset($sizes['medium_large']);
			return $sizes;
		}, 10, 1);
	}

	//移除.recentcomments样式
	private function remove_recentcomments_style() {
		add_action('widgets_init', function() {
			global $wp_widget_factory;
			remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style'));
		});
	}

	//移除Block Library样式
	private function remove_block_library_style() {
		add_action('wp_enqueue_scripts', function() {
			wp_dequeue_style('wp-block-library');
		});
	}

	//移除global-styles-inline-css
	private function global_styles_inline_css() {
		add_action('wp_print_styles', function() {
			wp_deregister_style('global-styles');
		});
	}

	//增加WebP格式支持
	private function add_webp() {
		add_filter('plupload_default_settings', function($defaults) {
			$defaults['webp_upload_error'] = false;
			return $defaults;
		}, 10, 1);
	
		add_filter('plupload_init', function($plupload_init) {
			$plupload_init['webp_upload_error'] = false;
			return $plupload_init;
		}, 10, 1);
	}

	//密码增强，使用Blowfish算法
	private function passwd_blowfish() {
		if(!function_exists('wp_hash_password')) {
			function wp_hash_password($password) {
				require_once(ABSPATH . WPINC . '/class-phpass.php');
				$wp_hasher = new PasswordHash(16, false);
				return $wp_hasher->HashPassword(trim($password));
			}
		}
	}

	//Gravatar头像CDN
	private function gravatar_cdn() {
		add_filter('get_avatar_url', function($url) {
			$url = preg_replace('/(?:http|https):\/\/\S+gravatar.com\/avatar\/(\S+)/', 'https://cravatar.cn/avatar/$1', $url);
			return $url;
		}, 10, 1);
	}

	//CDN
	private function cdn_replace() {
		//添加常规选项
		add_action('admin_init', function() {
			register_setting('general', 'cdn_domain', [
				'type' => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default' => NULL,
			]);
	
			add_settings_field('cdn-domain', '<label for="cdn-domain">CDN域名</label>', function() {
				echo '<input name="cdn_domain" type="text" id="cdn-domain" value="' . get_option('cdn_domain') . '" class="regular-text code">';
				echo '<p class="description">填写CDN域名，推荐使用<a href="https://curl.qcloud.com/0hUzGtOR" target="_blank" rel="noopener nofollow">腾讯云CDN</a></p>';
			}, 'general');
		});
		
		//替换为CDN域名
		add_action('wp_loaded', function() {
			if(is_admin() || in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'))) return;
	
			ob_start(function($html) {
				$cdn_domain = get_option('cdn_domain');
				if(!$cdn_domain) return $html;
	
				$site_url = get_option('siteurl') . '/';
				$cdn_url = parse_url($site_url, PHP_URL_SCHEME) . '://' . $cdn_domain . '/';
				$suffix = 'jpg|jpeg|png|gif|webp|mp3|wma|mp4|avi|webm|swf|flv|rmvb|css|js';
	
				$site_url = preg_quote($site_url, '/');
				$path = 'wp-includes|wp-content';
				$upload_path = get_option('upload_path', 'wp-content/uploads');
				if($upload_path != 'wp-content/uploads') $path .= '|' . preg_quote($upload_path);
				$pattern = '/(<.*?[src|href]=["|\'])' . $site_url . '((?:' . $path . ')\/.*?\.(?:' . $suffix . ')["|\'].*?>)/i';
				$replacement = "$1$cdn_url$2";
	
				$html = preg_replace($pattern, $replacement, $html);
				return $html;
			});
		});
	}
}
?>
